package com.fancy.learncenter.ui.activity;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CategoryDataBean;
import com.fancy.learncenter.bean.CategoryListDataBean;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.ActivityCategoryVedioAdapter;
import com.fancy.learncenter.ui.adapter.CategoryAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.ui.view.CustomFootView;
import com.fancy.learncenter.ui.view.CustomHeaderView;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class VedioCategoryActivity extends BaseActivity {

    ArrayList<CategoryDataBean> listData = new ArrayList<>();
    CategoryAdapter recycleAdapter;

    int id = 0;
    int type = 0;
    ActivityCategoryVedioAdapter vedioAdapter;
    List<CategoryListDataBean.ListBean> vedioListData;

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.back_ll)
    RelativeLayout backLl;
    @Bind(R.id.flag)
    View flag;
    @Bind(R.id.chanll_ll)
    LinearLayout chanllLl;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.top_bg)
    RelativeLayout topBg;
    @Bind(R.id.root)
    LinearLayout root;
    @Bind(R.id.vedio_List)
    RecyclerView vedioList;

    LinearLayout introRootView;
    TextView introduce;
    @Bind(R.id.xRefreshView)
    XRefreshView xRefreshView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vedio_category, Status.STATUS);
        ButterKnife.bind(this);

        introRootView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_vedio_category_intro, null);
        introduce = (TextView) introRootView.findViewById(R.id.introduce);
        bannerId = getIntent().getIntExtra("id", 0);
        initTopRecycleView(recyclerView, listData);
        initVedioRecycleView();
        flag.setBackgroundColor(getResources().getColor(R.color.yello));
        title.setText(getIntent().getStringExtra("name"));
        getBannerData();
    }


    private void initVedioRecycleView() {
        vedioListData = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
//        manager.setOrientation(LinearLayoutManager.VERTICAL);
        vedioList.setLayoutManager(manager);

        vedioAdapter = new ActivityCategoryVedioAdapter(this, vedioListData);

        vedioAdapter.setHeaderView(introRootView, vedioList);

        vedioList.setAdapter(vedioAdapter);

        xRefreshView.setPullLoadEnable(true);

        xRefreshView.setCustomHeaderView(new CustomHeaderView(this));

        vedioAdapter.setCustomLoadMoreView(new CustomFootView(this));

        xRefreshView.setAutoLoadMore(true);

        xRefreshView.setPinnedTime(1000);

        xRefreshView.setMoveForHorizontal(true);

        xRefreshView.setXRefreshViewListener(new XRefreshView.XRefreshViewListener() {
            @Override
            public void onRefresh() {
                getCategoryListData(id, type, true);
            }

            @Override
            public void onRefresh(boolean isPullDown) {

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                getCategoryListData(id, type, false);
            }

            @Override
            public void onRelease(float direction) {

            }

            @Override
            public void onHeaderMove(double headerMovePercent, int offsetY) {

            }
        });
    }

    private void addCater(List<CategoryDataBean> arrayList, int hor) {
        if (arrayList != null && arrayList.size() > 0) {
            RecyclerView recyclerView = (RecyclerView) LayoutInflater.from(this).inflate(R.layout.fragment_recycleview, root, false);

            if (hor == 1) {
                initThreRecycleView(recyclerView, arrayList);
            } else {
                initRecycleView(recyclerView, arrayList);
            }
            root.addView(recyclerView);
        }
    }


    private void initRecycleView(RecyclerView recyclerView, List<CategoryDataBean> datas) {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);

        CategoryAdapter adapter = new CategoryAdapter(this, datas) {
            @Override
            public void bindView(CustomViewHold customViewHold, final CategoryDataBean item, final int position) {
                TextView titile = customViewHold.getView(R.id.titile);
                titile.setText(item.getName());
                if (item.isSlect()) {
                    titile.setTextColor(Color.parseColor("#FFC300"));
                } else {
                    titile.setTextColor(Color.parseColor("#4a4a4a"));
                }
                customViewHold.getRoorView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        ToastUtil.show("第二层");
                        for (int i = 0; i < getItemDatas().size(); i++) {
                            getItemDatas().get(i).setSlect(false);
                        }
                        getItemDatas().get(position).setSlect(true);
                        getAdapter().notifyDataSetChanged();

                        initRoot(item.getCategoryDataBeans(), getItemDatas(), 1, position);
                    }
                });
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void initThreRecycleView(RecyclerView recyclerView, List<CategoryDataBean> datas) {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);

        CategoryAdapter adapter = new CategoryAdapter(this, datas) {
            @Override
            public void bindView(CustomViewHold customViewHold, final CategoryDataBean item, final int position) {
                TextView titile = customViewHold.getView(R.id.titile);
                titile.setText(item.getName());
                if (item.isSlect()) {
                    titile.setTextColor(Color.parseColor("#FFC300"));
                } else {
                    titile.setTextColor(Color.parseColor("#4a4a4a"));
                }
                customViewHold.getRoorView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < getItemDatas().size(); i++) {
                            getItemDatas().get(i).setSlect(false);
                        }
                        getItemDatas().get(position).setSlect(true);
                        getAdapter().notifyDataSetChanged();
//                        ToastUtil.show("第三层");
//                        initRoot(item.getCategoryDataBeans(), 1, position);

                        id = getItemDatas().get(position).getId();
                        type = getItemDatas().get(position).getType();

                        LogUtil.MyLog("addCater", id + "========addCater=====" + type);

                        getCategoryListData(id, type, true);
                    }
                });
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void initTopRecycleView(RecyclerView recyclerView, List<CategoryDataBean> datas) {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);

        recycleAdapter = new CategoryAdapter(this, datas) {
            @Override
            public void bindView(CustomViewHold customViewHold, CategoryDataBean item, final int position) {
                TextView titile = customViewHold.getView(R.id.titile);
                titile.setText(item.getName());
                if (item.isSlect()) {
                    titile.setTextColor(Color.parseColor("#FFC300"));
                } else {
                    titile.setTextColor(Color.parseColor("#FFFFFF"));
                }
                customViewHold.getRoorView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        for (int i = 0; i < recycleAdapter.itemDatas.size(); i++) {
                            recycleAdapter.itemDatas.get(i).setSlect(false);
                        }
                        recycleAdapter.itemDatas.get(position).setSlect(true);
                        recycleAdapter.notifyDataSetChanged();

                        initRoot(listData, listData, 0, position);
                    }
                });
            }
        };
        recyclerView.setAdapter(recycleAdapter);
    }


    int bannerId = 0;

    private void getBannerData() {
        Map<String, Object> paramer = new HashMap<>();
        paramer.put("id", bannerId);
        paramer.put("type", "1");
        paramer.put("hasTag", false);


        HttpMehtod.getInstance().getShowBanner(paramer, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                String result = NetUtil.getResResult(responseBodyResponse);

                try {
                    JSONObject jsonObject = new JSONObject(result);

                    JSONObject obj = (JSONObject) jsonObject.get("data");

                    JSONObject category = (JSONObject) obj.get("category");

                    String jsonDec = (String) category.get("categoryDesc");
                    if (!TextUtils.isEmpty(jsonDec)) {
                        introduce.setText(jsonDec);
                    }


                    JSONArray jsonArray = (JSONArray) category.get("categoryList");
                    JSONObject root = (JSONObject) jsonArray.get(0);

                    String start = root.getString("bgColorStart");
                    int startColor = Color.parseColor(start);
                    String end = root.getString("bgColorEnd");
                    int endColor = Color.parseColor(end);
                    int colors[] = {startColor, endColor};

                    GradientDrawable drawable = (GradientDrawable) topBg.getBackground();
                    drawable.setColors(colors);

                    getData(listData, root.getJSONArray("categoryList"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                recycleAdapter.notifyDataSetChanged();

                if (listData.size() > 0) {
                    listData.get(0).setSlect(true);
                    initRoot(listData, listData, 0, 0);
                }
            }
        });
    }

    private void initRoot(List<CategoryDataBean> listData, List<CategoryDataBean> rootData, int hor, int ver) {
        if (hor == 0) {
            root.removeAllViews();
            List<CategoryDataBean> twoData = listData.get(ver).getCategoryDataBeans();
            id = listData.get(ver).getId();
            type = listData.get(ver).getType();

            if (twoData != null && twoData.size() > 0) {

                for (int i = 0; i < twoData.size(); i++) {
                    twoData.get(i).setSlect(false);
                }
                twoData.get(0).setSlect(true);
                id = twoData.get(0).getId();
                type = twoData.get(0).getType();
                addCater(listData.get(ver).getCategoryDataBeans(), 0);
                List<CategoryDataBean> thrData = twoData.get(0).getCategoryDataBeans();
                if (thrData != null && thrData.size() > 0) {
                    for (int i = 0; i < thrData.size(); i++) {
                        thrData.get(i).setSlect(false);
                    }
                    thrData.get(0).setSlect(true);
                    id = thrData.get(0).getId();
                    type = thrData.get(0).getType();

                    addCater(thrData, 1);
                }
            }
        } else if (hor == 1) {
            if (root.getChildAt(1) != null) {
                root.removeViewAt(1);
            }

            id = rootData.get(ver).getId();
            type = rootData.get(ver).getType();

            addCater(listData, 1);
        }

        LogUtil.MyLog("addCater", id + "=======all=addCater=====" + type);

        getCategoryListData(id, type, true);
    }

    private void getData(List<CategoryDataBean> list, JSONArray jsonArray) {
        try {
            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject temp = (JSONObject) jsonArray.get(i);
                    CategoryDataBean categoryDataBean = new CategoryDataBean();
                    categoryDataBean.setName((String) temp.get("name"));
                    categoryDataBean.setId(Integer.parseInt(temp.getString("id")));
                    categoryDataBean.setType(Integer.parseInt(temp.getString("type")));
                    List<CategoryDataBean> data = new ArrayList<>();
                    getData(data, temp.getJSONArray("categoryList"));
                    categoryDataBean.setCategoryDataBeans(data);
                    list.add(categoryDataBean);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.MyLog("categoryList", "========categoryList======" + e);
        }
    }

    int curPage = 1;
    int pageSize = 10;

    private void getCategoryListData(int id, int type, final boolean refresh) {
        getIntroduceData(id);
        LogUtil.MyLog("getCategoryListData", id + "===getCategoryListData==" + type);

        Map<String, Object> paramer = new HashMap<>();
        paramer.put("id", id);
        paramer.put("type", type);

        if (refresh) {
            curPage = 1;
            paramer.put("curPage", curPage);
        } else {
            curPage++;
            paramer.put("curPage", curPage);
        }

        paramer.put("pageSize", pageSize);


        HttpMehtod.getInstance().getShowCategory(paramer, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<CategoryListDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CategoryListDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CategoryListDataBean>() {
                    @Override
                    public void success(CategoryListDataBean dataBean) {

                        if (refresh) {
                            if (dataBean.getList() != null) {
                                vedioAdapter.notifyDataSetChanged(dataBean.getList());
                            }
                            xRefreshView.stopRefresh();

                            if (dataBean.getList().size() < pageSize) {
                                xRefreshView.setLoadComplete(true);
                            } else {
                                xRefreshView.setLoadComplete(false);
                            }

                        } else {
                            if (dataBean.getList() != null) {
                                vedioAdapter.addAll(dataBean.getList());

                                if (dataBean.getList().size() < pageSize) {
                                    xRefreshView.setLoadComplete(true);
                                } else {
                                    xRefreshView.stopLoadMore();
                                }

                            } else {
                                xRefreshView.setLoadComplete(true);
                            }

                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
            }
        });
    }


    private void getIntroduceData(int bannerId) {
        Map<String, Object> paramer = new HashMap<>();
        paramer.put("id", bannerId);
        paramer.put("type", "1");
        paramer.put("hasTag", true);


        HttpMehtod.getInstance().getShowBanner(paramer, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                String result = NetUtil.getResResult(responseBodyResponse);

                try {
                    JSONObject jsonObject = new JSONObject(result);

                    JSONObject obj = (JSONObject) jsonObject.get("data");

                    JSONObject category = (JSONObject) obj.get("category");

                    String jsonDec = (String) category.get("categoryDesc");
                    if (!TextUtils.isEmpty(jsonDec)) {
                        introduce.setText(jsonDec);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
            }
        });
    }

    @OnClick(R.id.back)
    public void onClick() {
        this.finish();
    }
}
